//
//  ViewExt.swift
//  kano
//
//  Created by Sophia on 2024/8/14.
//

import UIKit

//MARK: frame
extension UIView {
    var x: CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            var frame: CGRect = self.frame;
            frame.origin.x = newValue;
            self.frame = frame;
        }
    }
    var y: CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            var frame: CGRect = self.frame;
            frame.origin.y = newValue;
            self.frame = frame;
        }
    }
    var width: CGFloat {
        get {
            return self.frame.size.width
        }
        set {
            var frame: CGRect = self.frame;
            frame.size.width = newValue;
            self.frame = frame;
        }
    }
    var height: CGFloat {
        get {
            return self.frame.size.height;
        }
        set {
            var frame: CGRect = self.frame;
            frame.size.height = newValue;
            self.frame = frame;
        }
    }
    
    var size: CGSize {
        get {
            return self.frame.size;
        }
        set {
            var frame: CGRect = self.frame;
            frame.size = newValue;
            self.frame = frame;
        }
    }
    var origin: CGPoint {
        get {
            return self.frame.origin;
        }
        set {
            var frame: CGRect = self.frame;
            frame.origin = newValue;
            self.frame = frame;
        }
    }
    var centerX: CGFloat {
        get {
            return self.center.x;
        }
        set {
            self.center.x = newValue
        }
    }
    var centerY: CGFloat {
        get {
            return self.center.y;
        }
        set {
            self.center.y = newValue
        }
    }
    var top: CGFloat {
        get {
            return self.frame.origin.y;
        }
        set {
            var frame: CGRect = self.frame;
            frame.origin.y = newValue;
            self.frame = frame;
        }
    }
    var bottom: CGFloat {
        get {
            return self.frame.origin.y + self.frame.size.height;
        }
        set {
            var frame: CGRect = self.frame;
            frame.origin.y = newValue - frame.size.height;
            self.frame = frame;
        }
    }
    var left: CGFloat {
        get {
            return self.frame.origin.x;
        }
        set {
            var frame: CGRect = self.frame;
            frame.origin.x = newValue;
            self.frame = frame;
        }
    }
    var right: CGFloat {
        get {
            return self.frame.origin.x + self.frame.size.width;
        }
        set {
            var frame: CGRect = self.frame;
            frame.origin.x = newValue - frame.size.width;
            self.frame = frame;
        }
    }
}


extension UIView {
    //MARK: currentVC
    func ka_viewController() -> UIViewController? {
        var var_next: UIResponder? = self.next
        while var_next != nil {
            if var_next!.isKind(of: UIViewController.self) {
                return var_next as? UIViewController
            }
            var_next = var_next?.next
        }
        return nil
    }
    
    func ka_removeAllSubviews() {
        for var_subView in self.subviews {
            var_subView.removeFromSuperview()
        }
    }
    //MARK: add line direction
    enum kaEnumBorderDirectionType: Int {
        case kaEnumBorderDirectionTop,kaEnumBorderDirectionLeft,kaEnumBorderDirectionBottom,kaEnumBorderDirectionRight
    }
    func ka_addLine(position: kaEnumBorderDirectionType, color: UIColor, width: CGFloat) {
        let var_line = CALayer()
        var_line.backgroundColor = color.cgColor
        switch position {
        case .kaEnumBorderDirectionLeft:
            var_line.frame = CGRect(x: 0, y: 0, width: width, height: self.height)
        case .kaEnumBorderDirectionRight:
            var_line.frame = CGRect(x: self.width-width, y: 0, width: width, height: self.height)
        case .kaEnumBorderDirectionTop:
            var_line.frame = CGRect(x: 0, y: 0, width: self.width, height: width)
        case .kaEnumBorderDirectionBottom:
            var_line.frame = CGRect(x: 0, y: self.height-width, width: self.width, height: width)
        }
        self.layer.addSublayer(var_line)
    }

    //MARK: search subview
    func ka_subView(of className: AnyClass) -> UIView? {
        if self.isKind(of: className) {
            return self
        }
        for var_subView in self.subviews {
            let var_view = var_subView.ka_subView(of: className)
            if var_view != nil {
                return var_view
            }
        }
        return nil
    }
    //MARK: search super view
    func ka_superView(of className: AnyClass) -> UIView? {
        if self.isKind(of: className) {
            return self
        }
        else if (self.superview != nil) {
            let var_view = self.superview?.ka_superView(of: className)
            if var_view != nil {
                return var_view
            }
        }
        return nil
    }
    
}

extension UIView {
    func ka_addCornerBorder(withRadius radius: CGFloat, color: UIColor) {
        layer.cornerRadius = kscale(28)
        layer.masksToBounds = true
        layer.borderWidth = 1
        layer.borderColor = color.cgColor
    }
    func ka_removeCornerBorder() {
        layer.cornerRadius = 0
        layer.masksToBounds = false
        layer.borderWidth = 0
        layer.borderColor = nil
    }
    
    func ka_addCorner(withRadius radius: CGFloat) {
        guard bounds.size.width > 0, bounds.size.height > 0 else {
            return
        }
        
        let bezierPath = UIBezierPath(roundedRect: bounds, cornerRadius: radius)
        let maskLayer = CAShapeLayer()
        maskLayer.path = bezierPath.cgPath
        layer.mask = maskLayer
    }
    
    func ka_addTopLeftAndRightBottomCorner(withRadius radius: CGFloat) {
        guard bounds.size.width > 0, bounds.size.height > 0 else {
            return
        }
        
        let bezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .bottomRight], cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.path = bezierPath.cgPath
        layer.mask = maskLayer
    }
    
    func ka_addTopCorner(withRadius radius: CGFloat) {
        guard bounds.size.width > 0, bounds.size.height > 0 else {
            return
        }
        
        let bezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.path = bezierPath.cgPath
        layer.mask = maskLayer
    }
    
    func ka_addBottomCorner(withRadius radius: CGFloat) {
        guard bounds.size.width > 0, bounds.size.height > 0 else {
            return
        }
        
        let bezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.path = bezierPath.cgPath
        layer.mask = maskLayer
    }
    
    func ka_addShadowAndCornerRadius(cornerRadius: CGFloat, shadowColor: UIColor, shadowOpacity: Float, shadowOffset: CGSize, shadowRadius: CGFloat) {
          self.layer.cornerRadius = cornerRadius
          self.layer.masksToBounds = false
          self.layer.shadowColor = shadowColor.cgColor
          self.layer.shadowOpacity = shadowOpacity
          self.layer.shadowOffset = shadowOffset
          self.layer.shadowRadius = shadowRadius
      }
}

extension UIView {
    
    func addHorizontalGradientLayer(startColor: CGColor, endColor: CGColor) -> CAGradientLayer {
        return addGradientLayer(
            startColor: startColor,
            endColor: endColor,
            startPoint: CGPoint(x: 0, y: 0.5),   // 水平方向起点
            endPoint: CGPoint(x: 1, y: 0.5)      // 水平方向终点
        )
    }
    func addVerticalGradientLayer(startColor: CGColor, endColor: CGColor) -> CAGradientLayer {
        return addGradientLayer(
            startColor: startColor,
            endColor: endColor,
            startPoint: CGPoint(x: 0.5, y: 0),   // 垂直方向起点
            endPoint: CGPoint(x: 0.5, y: 1.0)    // 垂直方向终点
        )
    }
    
    func addGradientLayer(startColor: CGColor, endColor: CGColor, startPoint: CGPoint, endPoint: CGPoint) -> CAGradientLayer {
        
        // 移除已有的渐变层
        removeGradientLayer()
        
        // 创建并配置渐变层
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.bounds
        gradientLayer.colors = [startColor, endColor]
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        
        // 设置自定义标记（如需）
        gradientLayer.name = "customGradientLayer"
        
        // 将渐变层插入到视图的最底层
        self.layer.insertSublayer(gradientLayer, at: 0)
        
        return gradientLayer
    }
    
    // 移除已有的渐变层
    func removeGradientLayer() {
        if let sublayers = self.layer.sublayers {
            for layer in sublayers {
                if let gradientLayer = layer as? CAGradientLayer, gradientLayer.name == "customGradientLayer" {
                    gradientLayer.removeFromSuperlayer()
                }
            }
        }
    }
}


//HUD
extension UIView {
    // 定义静态属性作为关联对象的键
    private struct AssociatedKeys {
        static var customButtonKey = "customButtonKey"
    }
    
    // 关联的 UIButton 实例
    var customButton: UIButton? {
        get {
            // 获取关联的 UIButton 对象
            return objc_getAssociatedObject(self, &AssociatedKeys.customButtonKey) as? UIButton
        }
        set {
            // 如果有新的 UIButton 设置为 customButton
            if let newButton = newValue {
                // 将 UIButton 关联到 UIView 实例
                objc_setAssociatedObject(self, &AssociatedKeys.customButtonKey, newButton, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                
                // 添加按钮到当前视图上
                self.addSubview(newButton)
            } else {
                // 如果 newValue 为 nil，移除 UIButton
                customButton?.removeFromSuperview()
                objc_setAssociatedObject(self, &AssociatedKeys.customButtonKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
    func showLoading() {
        let button = UIButton(frame: frame)
        button.backgroundColor = .black.withAlphaComponent(0.02)
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        customButton = button
        makeToastActivity(.center)
    }
    
    func hideLoading() {
        customButton = nil
        hideToastActivity()
    }
    
    
    @objc func buttonTapped() {
        
    }
}
